import { useState, useRef } from 'react'
import { GetGoodsFnc, DeleteProductsFnc } from '@/services/goods'
import type { ActionType } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components' 
import { Button, Modal, message } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import EditBox from './components/Edit';
import { useNavigate } from '@umijs/max';


const Goods = () => {
  const actionRef: any = useRef<ActionType>()
  const [modal, contextHolder] = Modal.useModal()
  const navigate = useNavigate()

  const [paramsAll, setParamsAll] = useState({ query: '' });
  const [pageSize, setPageSize] = useState(2); // table 每页显示的条数
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false); // 添加修改用户的盒子
  const [goodsID, setGoodsID] = useState('') // 商品ID

  // 表格数据初始化
  const getData = async (params: any) => {
    const res = await GetGoodsFnc({
      query: params.query,
      pagenum: current,
      pagesize: params.pageSize,
    })
    let arr = res.data.goods.map((item: any, index: number) => {
      return {
        key: index + 1,
        id: item.goods_id,
        goods_name: item.goods_name,
        goods_price: item.goods_price,
        goods_weight: item.goods_weight,
        add_time: item.add_time
      }
    })
    setTotal(res.data.total)
    return {
      data: arr,
      success: res.meta.status === 200,
      total: res.data.total,
    };
  }

  // 创建时间
  const createTime = (time: string) => {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1 + '').padStart(2, '0')
    const d = (date.getDate() + '').padStart(2, '0')
    const h = (date.getHours() + '').padStart(2, '0')
    const f = (date.getMinutes() + '').padStart(2, '0')
    const m = (date.getSeconds() + '').padStart(2, '0')
    return `${year}-${month}-${d} ${h}:${f}${m}`
  }

  // 打开 修改盒子 给子组件使用
  const openBox = (flag: boolean, ...args: any[]) => {
    setIsModalOpen(flag)
    setGoodsID(args[0])
  }

  // 删除商品
  const deleteGoods = async (id: number) => {
    modal.confirm({
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除用户, 是否继续?',
      onOk: async () => {
        const res = await DeleteProductsFnc(id)
        if (res.meta.status === 200) {
          message.open({
            type: 'success',
            content: '删除成功',
            duration: 1.5,
            onClose: () => {
            if (total % pageSize === 1) {
              setCurrent(current - 1)
            }
            actionRef.current?.reload()
            }
          })
        }
      }
    })
  }

  const columns: any = [
    {dataIndex: 'key', width: 50},
    {title: '商品名称', dataIndex: 'goods_name', key: 'goods_name', width: 400, ellipsis: true},
    {title: '商品价格', dataIndex: 'goods_price', key: 'goods_price', width: 70},
    {title: '商品重量', dataIndex: 'goods_weight', key: 'goods_weight', width: 70},
    {title: '创建时间', dataIndex: 'add_time', key: 'add_time',width: 120, ellipsis: true, render: (_: any, record: {add_time: string}) => createTime(record.add_time)},
    {title: '操作', width: 180, render: (info: {id: number, username: string, role_name: string}) => {
      return (
      <>
        <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => openBox(true, info.id)}>编辑</Button> 
        <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteGoods(info.id)} style={{margin: '0 6px 0'}}>删除</Button> 
      </>
      )
    }}
 ]   
  return (
    <>
     {contextHolder}
     <PageContainer header={{ title: '', breadcrumb: { items: [{ title: '商品管理' }, { title: '商品列表' }]}}}>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        rowKey={(record) => record.id}
        params={paramsAll}
        request={async (params) => getData(params)}
        scroll={{ x: 500 }}
        bordered
        search={false}
        toolbar={{
            search: {
              onSearch: (val) => {
                setParamsAll({ query: val })
                setCurrent(1)
              },
              placeholder: '请输入商品名',
              allowClear: true,
            },
            actions: [
              <Button
                type="primary"
                key={1}
                onClick={() => navigate('/C/addGoods')}
              >
                添加商品
              </Button>,
            ],
        }}
        onChange={({ current }: any) => setCurrent(current)}
        pagination={{
          pageSize: pageSize,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          onShowSizeChange: (_, size) => setPageSize(size)
        }}
      />
     </PageContainer>

     {/* 编辑盒子 */}
     <EditBox isModalOpen={isModalOpen} openBox={openBox} goodsID={goodsID} actionRef={actionRef}/>
    </>
  )
}

export default Goods